package com.huanglj.himalaya.activitys;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.huanglj.himalaya.R;
import com.huanglj.himalaya.adapters.AlbumAdapter;
import com.huanglj.himalaya.adapters.SearchResultAdapter;
import com.huanglj.himalaya.base.BaseActivity;
import com.huanglj.himalaya.base.BaseApplication;
import com.huanglj.himalaya.interfaces.ISearchCallBack;
import com.huanglj.himalaya.presenters.AlbumDetailPresenter;
import com.huanglj.himalaya.presenters.SearchPresenter;
import com.huanglj.himalaya.utils.LogUtil;
import com.huanglj.himalaya.views.FlowTextLayout;
import com.huanglj.himalaya.views.UILoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.huanglj.himalaya.utils.Constants.HOT_TOP_SP;

public class SearchActivity extends BaseActivity implements View.OnClickListener, ISearchCallBack, UILoader.OnRetryClickListener, AlbumAdapter.OnRecommendItemClickListener {

    private static final String TAG = "SearchActivity";

    private EditText mSearchText;
    private Button mSearchButton;
    private View mBackButton;
    private FrameLayout mResultContainer;
    private String mKeyword;
    private SearchPresenter mSearchPresenter;
    private List<String> mStringWords = new ArrayList<>();
    private FlowTextLayout mFlowTextLayout;
    private UILoader mUiLoader;
    private AlbumAdapter mAdapter;
    private RecyclerView mResultSuccessView;
    private InputMethodManager mInputMethodManager;
    private ImageView mDeleteBtn;
    private SharedPreferences mPreferences;
    List<String> spHotTop = new ArrayList<>();
    private RecyclerView mSuggestView;
    private SearchResultAdapter mSuggestAdapter;
    private TwinklingRefreshLayout mRefreshLayout;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mPreferences = BaseApplication.getContext().getSharedPreferences(HOT_TOP_SP,0);
        initView();
        initEvent();
        initPresenter();
    }

    private void initPresenter() {
        mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        mSearchPresenter = SearchPresenter.getInstance();
        mSearchPresenter.getHotWord();
        mSearchPresenter.registerViewCallBack(this);
    }

    private void initEvent() {
        mBackButton.setOnClickListener(this);
        mSearchButton.setOnClickListener(this);
        mDeleteBtn.setOnClickListener(this);
        mUiLoader.setOnRetryClickListener(this);
        mSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mFlowTextLayout.setVisibility(View.VISIBLE);
                    mFlowTextLayout.setTextContents(mStringWords);
                    mUiLoader.setVisibility(View.GONE);
                    mSuggestView.setVisibility(View.GONE);
                }else {

                    BaseApplication.getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getSuggestWord(s.toString());
                        }
                    },1000);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //这样获取数据
                mKeyword = s.toString().trim();
                //或者：mKeyword = mSearchText.getText().toString();
            }
        });
        //增加键盘点击搜索事件
        mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (mKeyword != null) {
                    mSearchPresenter.doSearch(mKeyword);
                    mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
                    return true;
                }
                return false;
            }
        });
        mFlowTextLayout.setClickListener(new FlowTextLayout.ItemClickListener() {
            @Override
            public void onItemClick(String text) {
                //TODO:执行热词点击逻辑
                mSearchText.setText(text);
                mSearchText.setSelection(text.length());
                if (mKeyword != null) {
                    mFlowTextLayout.setVisibility(View.GONE);
                    mSearchPresenter.doSearch(mKeyword);
                    mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
                }
            }
        });


        //设置适配器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mSuggestView.setLayoutManager(layoutManager);
        mSuggestAdapter = new SearchResultAdapter();
        mSuggestView.setAdapter(mSuggestAdapter);

        //设置联想词点击事件
        mSuggestAdapter.setOnSuggestItemClickListener(new SearchResultAdapter.OnSearchItemClickListener() {
            @Override
            public void onItemClick(Integer tag, QueryResult result) {
                mSearchText.setText(result.getKeyword());
                mSearchPresenter.doSearch(result.getKeyword());
                mFlowTextLayout.setVisibility(View.GONE);
                mSuggestView.setVisibility(View.GONE);
                mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
            }
        });



    }

    private void getSuggestWord(String keyword) {
        if(mSearchPresenter!=null){
            mSearchPresenter.getRecommendWord(keyword);
        }
    }

    private void initView() {
        mSearchText = findViewById(R.id.search_edit_text);
        mSearchText.postDelayed(new Runnable() {
            @Override
            public void run() {
                mSearchText.requestFocus();
                mInputMethodManager.showSoftInput(mSearchText,InputMethodManager.SHOW_FORCED);
            }
        },500);
        mSearchButton = findViewById(R.id.search_text_btn);
        mBackButton = findViewById(R.id.search_icon_button);
        mResultContainer = findViewById(R.id.search_container);
        mFlowTextLayout = findViewById(R.id.flow_text_view);
        mDeleteBtn = findViewById(R.id.search_delete_text);

        mUiLoader = new UILoader(this) {
            @Override
            protected View getSuccessView() {
                return createSuccessView();
            }
        };
        if(mUiLoader.getParent() instanceof ViewGroup){
            ((ViewGroup) mUiLoader.getParent()).removeView(mUiLoader);
        }
        mResultContainer.addView(mUiLoader);
        mSuggestView = findViewById(R.id.search_suggest_item);
    }

    private View createSuccessView() {
        View successView = LayoutInflater.from(this).inflate(R.layout.search_result_view, null, false);
        mResultSuccessView = successView.findViewById(R.id.result_success_view);
        mRefreshLayout = successView.findViewById(R.id.refreshLayout);
        mRefreshLayout.setEnableRefresh(false);
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mResultSuccessView.setLayoutManager(linearLayoutManager);
        //设置适配器
        mAdapter = new AlbumAdapter();
        mResultSuccessView.setAdapter(mAdapter);
        mResultSuccessView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.bottom = UIUtil.dip2px(view.getContext(), 0.5);
                outRect.top = UIUtil.dip2px(view.getContext(),0.5);
            }
        });

        //刷新事件的监听
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                mSearchPresenter.loadMore();
            }
        });

        mAdapter.setOnRecommendItemClickListener(this);
        return successView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_icon_button:
                finish();
                break;
            case R.id.search_text_btn:
                //TODO:调用搜索逻辑
                if (mKeyword != null && mKeyword.length() != 0) {
                    mFlowTextLayout.setVisibility(View.GONE);
                    mSuggestView.setVisibility(View.GONE);
                    mSearchPresenter.doSearch(mKeyword);
                    mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
                }else {
                    mFlowTextLayout.setVisibility(View.VISIBLE);
                    mUiLoader.setVisibility(View.GONE);
                }
                break;
            case R.id.search_delete_text:
                if (mKeyword != null && mKeyword.length() != 0) {
                    mSearchText.setText("");
                }

        }
    }

    @Override
    public void onSearchResultLoaded(List<Album> result) {
        mRefreshLayout.finishLoadmore();
        mUiLoader.setVisibility(View.VISIBLE);
        mResultSuccessView.setVisibility(View.VISIBLE);
        //TODO:取消焦点
        mInputMethodManager.hideSoftInputFromWindow(mSearchText.getWindowToken(),0);
        if (mAdapter != null){
            mAdapter.setData(result);
        }
        mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);

    }

    @Override
    public void onHotWordLoaded(List<HotWord> result) {

        mFlowTextLayout.setVisibility(View.VISIBLE);
        LogUtil.d(TAG,"HotWord:  result.size: " + result.size());
        mStringWords.clear();
        for (HotWord hotWord : result) {
            String searchword = hotWord.getSearchword();
            mStringWords.add(searchword);
            //做个缓存
            //SharedPreferences.Editor edit = mPreferences.edit();
            //edit.putString(HOT_TOP_SP,searchword);
            //edit.commit();
        }
        Collections.sort(mStringWords);
        mFlowTextLayout.setTextContents(mStringWords);
    }

    @Override
    public void onLoadMoreResult(List<Album> result, boolean isOkay) {

    }

    @Override
    public void onRecommendWordLoader(List<QueryResult> result) {
        LogUtil.d(TAG,"SuggestSize: "+result.size());
        mSuggestAdapter.setData(result);
        mSuggestView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onError(int errorCode, String errorMsg) {
        mUiLoader.updateStatus(UILoader.UIStatus.NETWORK_ERROR);

    }

    @Override
    public void onEmpty() {
        mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSearchPresenter != null) {
            mSearchPresenter.unRegisterViewCallBack(this);
        }
    }

    @Override
    public void onRetryClick() {
        if (mKeyword != null) {
            mSearchPresenter.doSearch(mKeyword);
            mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
        }
    }

    @Override
    public void onItemClick(Integer tag, Album album) {
        AlbumDetailPresenter.getInstance().setTargetAlbum(album);
        Intent intent = new Intent(this,DetailActivity.class);
        startActivity(intent);
    }
}
